package org.example.Server.service.home;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.example.Server.mapper.home.CommentMapper;
import org.example.Server.mapper.home.HomeMapper;
import org.example.Server.model.commen.Direction;
import org.example.Server.model.home.*;
import org.example.Server.model.user.UserMute;
import org.example.Server.utils.PageResult;
import org.example.Server.utils.ResultAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;

import static org.example.Server.utils.BanWordsUtil.ERROR_WORD;
import static org.example.Server.utils.BanWordsUtil.TextCensor;

@Service
@Slf4j
public class HomeService {

    @Autowired
    private HomeMapper homeMapper;
    @Autowired
    CommentMapper commentMapper;

    /**
     * 调用mapper请求数据
     *
     * @param semCnt 前多少浏览量的课程
     * @return
     */
    public ResultAPI getSlider(int semCnt) {
        List<SlideShowDTO> sliders = homeMapper.getSlider(semCnt);
        return ResultAPI.success(sliders);
    }


    /**
     * 使用List接收值，防止有多个教师
     *
     * @param courseId 课程id
     * @return
     */
    public ResultAPI getCourseTeam(int courseId) {
        List<CourseTeamDTO> courseTeam = homeMapper.getCourseTeam(courseId);
        return ResultAPI.success(courseTeam);
    }


    /**
     * 将请求来的课程介绍拼接成html格式
     *
     * @param courseId 课程id
     * @return
     */
    public ResultAPI getCourseIntro(int courseId) {
        String data = homeMapper.getCourseIntro(courseId);
        data = "<p>" + data + "</p>";
        return ResultAPI.success(data);
    }

    /**
     * 使用pageHelper进行分页查询
     *
     * @param newReplyDTO
     * @return
     */
    public PageResult getNewReply(NewReplyDTO newReplyDTO) {
        PageHelper.startPage(newReplyDTO.getPage(), newReplyDTO.getPagesize());
        Page<NewReplyVO> result = homeMapper.selectByPageOrderByTime(newReplyDTO);
        long total = result.getTotal();
        List<NewReplyVO> record = result.getResult();
        log.info(record.toString());
        return new PageResult(total, record);
    }

    public PageResult getHotReply(NewReplyDTO newReplyDTO) {
        PageHelper.startPage(newReplyDTO.getPage(), newReplyDTO.getPagesize());
        Page<NewReplyVO> result = homeMapper.selectByPageOrderByComment(newReplyDTO);
        long total = result.getTotal();
        List<NewReplyVO> record = result.getResult();
        return new PageResult(total, record);
    }

    public PageResult getTypeReply(NewReplyDTO newReplyDTO) {
        PageHelper.startPage(newReplyDTO.getPage(), newReplyDTO.getPagesize());
        Page<NewReplyVO> result = homeMapper.selectByPageAndType(newReplyDTO);
        long total = result.getTotal();
        List<NewReplyVO> record = result.getResult();
        return new PageResult(total, record);
    }

    public TypeReplyVO getDetailReply(int postId, int page, int pageSize) {
        PageHelper.startPage(page, pageSize);
        Page<Comment> result = homeMapper.selectCommentByPostId(postId);
        Long total = result.getTotal();
        List<Comment> commentList = result.getResult();
        TypeReplyVO typeReplyVO = homeMapper.selectTopicById(postId);
        typeReplyVO.setCommentList(commentList);
        typeReplyVO.setData_cnt(total.intValue());
        return typeReplyVO;
    }

    /**
     * 发布话题
     *
     * @param post
     */
    public void setTopic(Post post) {
        post.setUpdate_time(LocalDateTime.now().toString());
        log.info("post:{}", post);
        homeMapper.insertPost(post);
    }

    /**
     * 获取方向
     */
    public ResultAPI getDirection() {
        List<Direction> directions = homeMapper.getDirection();
        return ResultAPI.success(directions);
    }

    /**
     * 获取data
     *
     * @return
     */
    public ResultAPI getHomeData() {
        HomeData homeData = homeMapper.getHomeData();
        return ResultAPI.success(homeData);
    }

    /**
     * 发送评论
     *
     * @param commentDTO
     * @return
     */
    public ResultAPI<PageResult> CommentReplyPost(CommentDTO commentDTO) {
        // 看这个用户有没有被禁言
        UserMute userMute = commentMapper.isUserMute(commentDTO.getUser_id());
        if (userMute != null) {
            StringBuilder mute = new StringBuilder();
            if (userMute.getIs_forever()) {
                mute.append("您已被禁言！\n");
                mute.append("禁言期限：永久\n");
                mute.append("禁言原因如下：\n");
                mute.append(userMute.getMute_reason()).append("\n");
            } else {
                mute.append("您已被禁言！\n");
                mute.append("开始时间：").append(userMute.getStart_time()).append("\n");
                mute.append("结束时间：").append(userMute.getEnd_time()).append("\n");
                mute.append("禁言原因如下：\n");
                mute.append(userMute.getMute_reason()).append("\n");
            }
            return ResultAPI.error(mute.toString());
        }
        // 进行敏感词判断
//        try {
//            String accessToken = getAccessToken();
//            log.info("accessToken:{}", accessToken);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResultAPI.error("敏感词过滤获取AccessToken出错");
//        }
        String inputText = commentDTO.getComment_content();
        String censorRes = TextCensor(inputText);
        //百度先判断
        if (censorRes.equals(ERROR_WORD)) {
            return ResultAPI.error("用户输入违规词语");
        } else {
            // 本地敏感词再判断
            List<String> banwords = commentMapper.getBanWords();
            log.info("banwords:{}", banwords);
            boolean flag = banwords.stream().anyMatch(inputText::contains);
            if (flag) {
                return ResultAPI.error("用户输入违规词语");
            }
        }
        // 存入数据库
        commentMapper.insertCommentReply(commentDTO);
        return ResultAPI.success();
    }


    public ResultAPI deleteComment(int id) {
        commentMapper.deleteComment(id);
        return ResultAPI.success();
    }

    public ResultAPI<Boolean> deleteTopic(Integer id) {
        commentMapper.deleteTopic(id);
        return ResultAPI.success();
    }
}
